<?php
require_once $ubi['SERVER']['SERVER_ROOT'] . '/controller/ctlAbstract.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/message.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/user.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/model/friend.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/utility/generalFunctions.php';

require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busMessage.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busUser.php';
require_once $ubi['SERVER']['SERVER_ROOT'] . '/business/busFriend.php';

class AddController extends AbstractController {
	private $_userBus;
	private $_friendBus;
	private $_messageBus;
	
	//begin class AddController
	public function main(array $getVars) {
		$this->_userBus = new UserBus();
		$this->_friendBus = new FriendBus();
		$this->_messageBus = new MessageBus();
		
		//begin main method of class AddController

		//check for type of add
		if ($getVars['type'] == 'friend') {
			//begin type of friend			
			if (isset($getVars['userid'])) {
				if ($_SESSION['userid']) {
					$friend = new FriendModel();
					
					$friend->setAccepted(false);
					$friend->setUserID($_SESSION['userid']);
					$friend->setFriendID($getVars['userid']);
					
					$isExist = $this->_friendBus->isExist($getVars['userid'], $_SESSION['userid']);
					
					if ($isExist == 0) {
						$friend->setAccepted(0);
						//send message to the the user that current user wants to add friend to confirm
						$u = $this->_userBus->getUser($getVars['userid']);
						
						$message = new MessageModel();
						$message->setReceiverId($getVars['userid']);
						$message->setSenderId($_SESSION['userid']);
						$message->setStatus(0);
						$message->setTitle($_SESSION['username'] . ' muốn kết nối với bạn');
						if (isset($_POST['content'])) {
							$content = $_POST['content'];
						} else {
							$content = "Xin chào " . $u->getUserName() . ".<br /> " . $_SESSION['username'] . "muốn kết bạn với bạn\n";						 
						}
						$content .= 'Để chấp nhận lời mời, bạn hãy click vào link sau <a class="a_cursor" onclick="$.makeFriend(' . $_SESSION['userid'] . ', $(this))">Thêm bạn</a>'; 
						$message->setContent($content);
												
						echo $this->_messageBus->addMessage($message);
					} else  {
						$friend->setAccepted(1);
						echo $this->_friendBus->updateFriendAccept($getVars['userid'], $_SESSION['userid']);
					}

					$this->_friendBus->addFriend($friend);
				}	
			} else {
				header('Location:' . 'index.php');
			}			
		}//end type of friend		
	}//end of main method of class AddController	
}//end of class AddController
?>